package com.ytjj.qmyx.mall.utils;

import com.google.gson.GsonBuilder;
import com.ytjj.common.utils.Aes128CBCUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class HFSoowareUtils {
    public static String encoding(Map<String, Object> headerMap, Map<String, Object> bodyMap, String key, String iv)
            throws Exception {
        Map<String, Object> m = new LinkedHashMap<>();
        m.put("header", headerMap);
        String json = new GsonBuilder().create().toJson(bodyMap);
        m.put("body", json);
        log.info(new GsonBuilder().create().toJson(m));
        m.put("body", Aes128CBCUtil.encrypt(json, key, iv));
        json = new GsonBuilder().create().toJson(m);
        return json;
    }

    public static String post(String orderUrl, Map<String, Object> headerMap, Map<String, Object> bodyMap, String key,
                              String iv) throws Exception {
        String json = encoding(headerMap, bodyMap, key, iv);
        return post(orderUrl, json);
    }

    public static String post(String strUrl, String json) throws Exception {
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStream out = conn.getOutputStream();
        log.info(json);
        out.write(json.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream response = new ByteArrayOutputStream();
        int i = -1;
        while ((i = in.read()) != -1) {
            response.write(i);
        }
        response.flush();
        return new String(new String(response.toByteArray(), "UTF-8"));
    }
}
